import { StoreOptions } from 'vuex'
import { IFileViewModel } from './ViewModels/FilesViewModel'
import http from '@/http';

interface IFilesState {
    curDir: IFileViewModel
    files: IFileViewModel[]
}

interface IRefresh {
    files: IFileViewModel[]
}

interface ISelectDir {
    curDir: IFileViewModel
}

interface IGetCurDirAsync {
    id: number
}

interface IGetFilesAsync {
    parentId: number
}

export const moduleFiles: StoreOptions<IFilesState> = {
    state: {
        curDir: <IFileViewModel>{
            id: 0,
            file_name: '/',
            is_dir: true,
            parent_index: null,
            created_at: (new Date()).getTime()
        },
        files: [] as IFileViewModel[]
    },
    getters: {

    },
    mutations: {
        selectDir(state, playload: ISelectDir) {
            state.curDir = playload.curDir
        },
        filesRefresh(state, playload: IRefresh) {
            state.files = playload.files
        }
    },
    actions: {
        async getCurDirAsync({ commit }, playload: IGetCurDirAsync) {
            let response = await http.get(`/api/Files/${playload.id}`)
            commit('selectDir', <ISelectDir>{ curDir: response.data })
        },
        async getFilesAsync({ commit }, playload: IGetFilesAsync) {
            let response = await http.get(`/api/Files?parent_id=${playload.parentId}`)
            commit('filesRefresh', <IRefresh>{ files: response.data })
        },
        createDirPromise({ commit }, playload: { parentId: number, name: string }) {
            return http.post(`/api/Dirs`, {
                parent_id: playload.parentId,
                name: playload.name
            });
        },
        createFilePromise({ commit }, playload: { parentId: number, file: File}) {
            let formData = new FormData();
            formData.append('file', playload.file);
            formData.append('parent_id', playload.parentId.toString());
            return http.post(`/api/Files`,
                    formData,
                    {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    });
        },
        deleteFile({ commit }, playload: { id: number }) {
            return http.delete(`/api/Files/${playload.id}`);
        }
    }
}